package com.czk.config;

import com.czk.dao.UserDao;
import com.czk.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/3/19 13:57
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    /**
     * 注入userdao
     */
    @Autowired
    private UserDao userDao;

    /**
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        UserDto userDto = userDao.loadByUsername(username);
        if (userDto == null) {
            // 框架会帮你抛出异常
            return null;
        }
        System.out.println("用户名是 " + username);
        // 拿到权限
        List<String> permissionByUserId = userDao.findPermissionByUserId(userDto.getId());
        // 将其转换为数组
        String[] permissionArray = new String[permissionByUserId.size()];
        permissionByUserId.toArray(permissionArray);
        // 打印权限列表
        System.out.println(Arrays.toString(permissionArray));
        // 将用户信息和权限加入
        UserDetails userDetails = User.withUsername(userDto.getUsername()).password("123").authorities(permissionArray).build();
        // 过滤器会拿到userDetail进行密码比对
        return userDetails;
    }
}
